package bi.uc.client;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.bi_uc.www.R;

import bi.uc.login.Info;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class QuickscoreActivity extends Activity implements OnClickListener, OnTouchListener, Runnable {

	EditText cardNum;
	String cardNumString;
	EditText score;
	String scoreString;
	Spinner spinOperation;
	String OperationType;
	ImageButton searchCardNum;
	Info info = Info.getInfo();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		((ExitApplication)getApplication()).addActivity(this);
		setContentView(R.layout.quickscore);
		cardNum = (EditText) findViewById(R.id.cardNum);
		if (info.isExist(info.card.cardNum))
			cardNum.setText(info.card.cardNum);
		
		score = (EditText) findViewById(R.id.score);
		spinOperation = (Spinner) findViewById(R.id.spinneroperation);
		searchCardNum = (ImageButton) findViewById(R.id.searchbtn);
		searchCardNum.setOnClickListener(this);
		searchCardNum.setOnTouchListener(this);
		spinOperation.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> ad, View v, int index,
					long id) {
				// TODO Auto-generated method stub
//				sexString = ad.getItemAtPosition(index).toString();
				OperationType = String.valueOf(index);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
	}
	
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.searchbtn:
			Intent intent = new Intent(this, ReadMemberInfoActivity.class);
			startActivityForResult(intent, 1);
			Toast.makeText(this, "读取卡号", Toast.LENGTH_SHORT).show();
			break;
		case R.id.btnOK:
			if (info.stopFlag) {
				Toast.makeText(this, "网络未连接，请确保您的网络已连接！", Toast.LENGTH_SHORT)
						.show();
			} else {
				apply();
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 
	 */
	private void apply() {
		// TODO Auto-generated method stub
		cardNumString = cardNum.getText().toString();
		scoreString = score.getText().toString();
		if ("".equals(cardNumString)) {
			Toast.makeText(this, "请输入卡号！", Toast.LENGTH_SHORT).show();
			return;
		}
		if ("".equals(scoreString)) {
			Toast.makeText(this, "请输入充值金额！！", Toast.LENGTH_SHORT).show();
			return;
		} else if (!scoreString.matches("[0-9]{1,}")) {
			Toast.makeText(this, "输入不合法，请确保输入均为数字！", Toast.LENGTH_SHORT).show();
			return;
		}
		new Thread(this).start();
	}

	/* (non-Javadoc)
	 * @see android.view.View.OnTouchListener#onTouch(android.view.View, android.view.MotionEvent)
	 */
	@Override
	public boolean onTouch(View view, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.searchbtn:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				searchCardNum.setBackgroundColor(Color.TRANSPARENT);
			}else if (event.getAction() == MotionEvent.ACTION_DOWN) {
				searchCardNum.setBackgroundColor(Color.rgb(51, 102, 153));
			}
			break;
		default:
			
			break;
		}
		return false;
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			send();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		  case 1:
		          if(resultCode==Activity.RESULT_OK){		        	  
		        	  cardNum.setText(info.card.cardNum);
		          }
		          break;
		   default:
			   break;
		  }
	}
	/**
	 * 
	 */
	private void send() throws Exception{
		// TODO Auto-generated method stub
		String Url = "http://bi.bi-uc.com/BI.api";
		/*String Body = "Action=PDA-充值&商家=" + info.employID + "&店面="
				+ info.shopID + "&操作员=" + info.userID + "&卡号=" + cardNumString
				+ "&充值金额=" + moneyString;
		Log.d("data", Body);*/
		HttpPost httpRequest = new HttpPost(Url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		NameValuePair pair1 = new BasicNameValuePair("Action", "PDA-快速积分");
		NameValuePair pair2 = new BasicNameValuePair("商家", info.employID);				
		NameValuePair pair3 = new BasicNameValuePair("卡号", cardNumString);
		NameValuePair pair4 = new BasicNameValuePair("店面", info.shopID);
		NameValuePair pair5 = new BasicNameValuePair("类型", OperationType);
		NameValuePair pair6 = new BasicNameValuePair("数量", scoreString);
		NameValuePair pair7 = new BasicNameValuePair("操作员", info.userID);
		params.add(pair1);
		params.add(pair2);
		params.add(pair3);
		params.add(pair4);
		params.add(pair5);
		params.add(pair6);
		params.add(pair7);
		HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
		httpRequest.setEntity(entity);
		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse response = client.execute(httpRequest);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			/*InputStream in = response.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));  
			StringBuffer responseMessage = new StringBuffer();
			int charCount = -1;  
			   while ((charCount = br.read()) != -1) {  
				    responseMessage.append((char) charCount);  
				   }  
			   Log.d("tag", responseMessage.toString());*/
			InputStream in = response.getEntity().getContent();// 接收服务器的数据
			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance();    // 获取XmlPullParser的实例					
			final XmlPullParser parser = pullParserFactory.newPullParser();
			InputStreamReader responseReader = new InputStreamReader(in,
					"UTF-8");
			parser.setInput(responseReader);
			parser.next();
			int eventType = parser.getEventType();
			if (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG
						&& parser.getName().equals("XML")) { // String result = parser.getAttributeValue(0);
					String result = parser.getAttributeValue(null, "EXEC");
					if (result.equals("True")) {
						if (cardNumString.equals(info.card.cardNum)) {
							if (OperationType.equals("0")) {
								info.card.score = info.card.score - Integer.parseInt(scoreString);	
							}else {
								info.card.score = info.card.score + Integer.parseInt(scoreString);
							}		
						}
																	
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Intent intent = getIntent();						 
								/* 将数据打包到aintent Bundle 的过程略 */
								setResult(RESULT_OK, intent); //这理有2个参数(int resultCode, Intent intent)															 
								finish();
								Log.d("data", "快速积分成功！");
							}
						});
						
					} else {							
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								Toast.makeText(QuickscoreActivity.this,
										"快速积分失败!" + parser.getAttributeValue(null, "错误消息"), Toast.LENGTH_SHORT)
										.show();
							}
						});
					}
				}
			}
			in.close();
		
			responseReader.close();
		}
		else
		{
			runOnUiThread(new Runnable() {				
				@Override
				public void run() {
					Toast.makeText(QuickscoreActivity.this, "连接超时，请确保网络连接正常！", Toast.LENGTH_SHORT).show();
					}
			});	
		}

	}
	
	
}
